﻿using System;
using System.Collections;
using System.IO;

namespace JCodeGen
{
    public class ResourcesManager
    {
        private static readonly string assemblyName;
        private static readonly string templatesRoot;

        static ResourcesManager()
        {
            assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            templatesRoot = "Templates";
        }

        private static ResourcesLoader _resourcesLoader;
        public static ResourcesLoader resourcesLoader
        {
            get
            {
                if (_resourcesLoader == null)
                    _resourcesLoader = new ResourcesLoader();
                return _resourcesLoader;
            }
        }

        private static Hashtable templates;
        public static string GetTemplate(string fileName)
        {
            if (templates == null)
                templates = new Hashtable();

            string template = (string)templates[fileName];

            if (template == null)
            {
                Stream stream = resourcesLoader.GetResource(fileName);

                if (stream == null)
                    throw new Exception("there is no Embedded Resources named " + fileName);

                StreamReader reader = new StreamReader(stream);
                
                template = reader.ReadToEnd();

                templates.Add(fileName, template);
            }
            return template;
        }

        
        public static string GetTemplate(CodeGenBase codeGen, CodeGenFileTypes codeGenFileTypes)
        {
            string codeGenType = codeGen.GetType().Name;
            string fileType = codeGenFileTypes.ToString();

            string filename = string.Format("{0}.{1}.{2}.{3}.tpl",
                                assemblyName,
                                templatesRoot,
                                codeGenType,
                                fileType);

            return GetTemplate(filename);
            //return filename;
        }


    } // end of ResourcesManager
}
